import urllib.request
import json
from city import city #导入city.py中的city

while True:
        cityname = input("你想要查询哪个城市的天气呢？\n")
        #如果输入了才开始执行
        if cityname:
                citycode = city.get(cityname)
                if citycode:
                        try:
                                url = 'http://www.weather.com.cn/data/cityinfo/%s.html' % citycode
                                content = urllib.request.urlopen(url).read().decode('utf-8') #注意此处读取到的不是字典，而是一个满足json格式的字符串
                                #print(content)
                                data = json.loads(content) #转成一个字典
                                result = data['weatherinfo']
                                str_temp = ('%s\n%s ~ %s') % (
                                        result['weather'],
                                        result['temp1'],
                                        result['temp2']
                                        )
                                print(str_temp)
                        except:
                                print("查询失败")
                else:
                        print('没有找到该城市')
        else:
                print("欢迎下次再来")
                break